/*
 * ObjectConverter.java
 *
 * Created on May 17, 2007, 5:40 PM
 *
 */

package com.vce.web.jsf;

import com.vce.Persistent;
import com.vce.util.ObjectLookup;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.web.jsf.FacesContextUtils;

/**
 *
 * @author lruiz
 */
public class ObjectConverter implements Converter{
    private ObjectLookup objectLookup;
    
    /** Creates a new instance of ObjectConverter */
    
    
    public void setObjectLookup(ObjectLookup objectLookup){
        this.objectLookup = objectLookup;
    }
    
    
    public ObjectConverter() {
    }
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String string) {
        Class clazz = getTargetClass(uiComponent, facesContext);
        if(StringUtils.hasText(string)){
            return getObjectLookup().find(new Long(string), clazz);
        }
        return null;
    }
    
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object object) {
        if(object == null || ((Persistent)object).getId() == null){
            return "";
        }
        return String.valueOf(((Persistent)object).getId());
    }
    
    
    public ObjectLookup getObjectLookup() {
        if(objectLookup == null){
            ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
            objectLookup = (ObjectLookup) ctx.getBean("objectLookup");
        }
        return objectLookup;
    }
    
    private Class getTargetClass(UIComponent uiComponent, FacesContext facesContext) {
        return uiComponent.getValueExpression("value").getType(facesContext.getELContext());
    }
}
